<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="navbar">
      <view class="back-btn" @click="navigateBack">
        <uni-icons type="left" size="24"></uni-icons>
      </view>
      <view class="title">{{ doctorName }}</view>
      <view class="right-space"></view>
    </view>
    
    <!-- 聊天内容区域 -->
    <view class="chat-content">
      <view v-for="(msg, index) in messageList" :key="index" class="message-item">
        <!-- 医生消息 -->
        <view class="doctor-message" v-if="msg.senderType === 1">
          <image :src="doctorAvatar" class="sender-avatar"></image>
          <view class="message-bubble doctor-bubble">
            <view class="message-content" v-if="msg.type === 1">{{ msg.content }}</view>
            <image 
              :src="msg.imageUrl" 
              class="message-image"
              mode="widthFix"
              v-if="msg.type === 2"
              @click="previewImage(msg.imageUrl)"
            ></image>
            <view class="message-time">{{ formatTime(msg.createTime) }}</view>
          </view>
        </view>
        
        <!-- 用户消息 -->
        <view class="user-message" v-if="msg.senderType === 2">
          <view class="message-bubble user-bubble">
            <view class="message-content" v-if="msg.type === 1">{{ msg.content }}</view>
            <image 
              :src="msg.imageUrl" 
              class="message-image"
              mode="widthFix"
              v-if="msg.type === 2"
              @click="previewImage(msg.imageUrl)"
            ></image>
            <view class="message-time">{{ formatTime(msg.createTime) }}</view>
          </view>
          <image :src="userAvatar" class="sender-avatar"></image>
        </view>
      </view>
    </view>
    
    <!-- 输入区域 -->
    <view class="chat-footer" v-if="sessionStatus === 0">
      <view class="tool-bar">
        <view class="tool-item" @click="chooseImage">
          <uni-icons type="image" size="24"></uni-icons>
        </view>
      </view>
      <view class="input-area">
        <textarea 
          v-model="messageContent" 
          placeholder="请输入消息..." 
          class="message-input"
          @confirm="sendMessage"
        ></textarea>
        <button class="send-btn" @click="sendMessage">发送</button>
      </view>
    </view>
    <view class="chat-footer ended" v-if="sessionStatus === 1">
      <text>会话已结束，无法发送消息</text>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      sessionId: '',
      doctorId: '',
      doctorName: '医生',
      doctorAvatar: '/static/images/doctor.png',
      userAvatar: '/static/images/user.png',
      sessionStatus: 0, // 0-活跃 1-已结束
      messageList: [],
      messageContent: '',
      socket: null
    };
  },
  onLoad(options) {
    this.sessionId = options.sessionId;
    this.doctorId = options.doctorId;
    this.doctorName = options.doctorName || '医生';
    
    this.initWebSocket();
    this.loadMessageList();
  },
  onUnload() {
    if (this.socket) {
      this.socket.close();
    }
  },
  methods: {
    // 返回上一页
    navigateBack() {
      uni.navigateBack();
    },
    
    // 初始化WebSocket
    initWebSocket() {
      const token = uni.getStorageSync('token');
      // 根据平台选择不同的协议
      const wsProtocol = uni.getSystemInfoSync().platform === 'ios' || uni.getSystemInfoSync().platform === 'android' 
        ? 'wss:' : 'ws:';
      
      const baseUrl = this.getBaseUrl();
      this.socket = new WebSocket(
        `${wsProtocol}//${baseUrl}/ws/user/doctor?token=${token}&sessionId=${this.sessionId}`
      );
      
      this.socket.onopen = () => {
        console.log('WebSocket连接成功');
      };
      
      this.socket.onmessage = (event) => {
        const message = JSON.parse(event.data);
        this.messageList.push(message);
        this.scrollToBottom();
      };
      
      this.socket.onerror = (error) => {
        console.error('WebSocket错误:', error);
        uni.showToast({
          title: '连接错误',
          icon: 'none'
        });
      };
      
      this.socket.onclose = () => {
        console.log('WebSocket连接关闭');
        // 尝试重连
        setTimeout(() => {
          this.initWebSocket();
        }, 3000);
      };
    },
    
    // 获取基础URL
    getBaseUrl() {
      // 实际项目中根据环境配置
      return 'your-domain.com';
    },
    
    // 加载消息列表
    loadMessageList() {
      uni.request({
        url: `/api/chat/doctor/list?sessionId=${this.sessionId}`,
        method: 'GET',
        header: {
          'Authorization': 'Bearer ' + uni.getStorageSync('token')
        },
        success: (res) => {
          if (res.data.code === 200) {
            this.messageList = res.data.rows;
            this.scrollToBottom();
          }
        }
      });
    },
    
    // 发送消息
    sendMessage() {
      if (!this.messageContent.trim()) {
        uni.showToast({
          title: '请输入消息内容',
          icon: 'none'
        });
        return;
      }
      
      const message = {
        doctorSessionId: this.sessionId,
        doctorMessageSenderId: uni.getStorageSync('userId'),
        doctorMessageSenderType: 2, // 2-用户
        doctorMessageReceiverId: this.doctorId,
        doctorMessageReceiverType: 1, // 1-医生
        doctorMessageContent: this.messageContent,
        doctorMessageType: 1 // 1-文本 2-图片
      };
      
      this.socket.send(JSON.stringify(message));
      this.messageContent = '';
    },
    
    // 选择图片
    chooseImage() {
      uni.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0];
          
          // 上传图片
          uni.uploadFile({
            url: '/api/common/upload',
            filePath: tempFilePath,
            name: 'file',
            header: {
              'Authorization': 'Bearer ' + uni.getStorageSync('token')
            },
            success: (uploadRes) => {
              const data = JSON.parse(uploadRes.data);
              if (data.code === 200) {
                const message = {
                  doctorSessionId: this.sessionId,
                  doctorMessageSenderId: uni.getStorageSync('userId'),
                  doctorMessageSenderType: 2, // 2-用户
                  doctorMessageReceiverId: this.doctorId,
                  doctorMessageReceiverType: 1, // 1-医生
                  doctorMessageContent: '',
                  doctorMessageType: 2, // 1-文本 2-图片
                  doctorMessageImageUrl: data.url
                };
                
                this.socket.send(JSON.stringify(message));
              }
            }
          });
        }
      });
    },
    
    // 预览图片
    previewImage(url) {
      uni.previewImage({
        urls: [url]
      });
    },
    
    // 格式化时间
    formatTime(time) {
      const date = new Date(time);
      return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    },
    
    // 滚动到底部
    scrollToBottom() {
      this.$nextTick(() => {
        const query = uni.createSelectorQuery().in(this);
        query.select('.chat-content').boundingClientRect(data => {
          const scrollHeight = data.height;
          uni.pageScrollTo({
            scrollTop: scrollHeight,
            duration: 0
          });
        }).exec();
      });
    }
  }
};
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
}

.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 44px;
  padding: 0 16px;
  background-color: #fff;
  border-bottom: 1px solid #eee;
}

.back-btn {
  width: 44px;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.right-space {
  width: 44px;
  height: 44px;
}

.chat-content {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  box-sizing: border-box;
}

.message-item {
  margin-bottom: 16px;
}

.doctor-message, .user-message {
  display: flex;
  align-items: flex-start;
}

.doctor-message {
  flex-direction: row;
}

.user-message {
  flex-direction: row-reverse;
}

.sender-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin: 0 10px;
}

.message-bubble {
  max-width: 70%;
  padding: 10px 12px;
  border-radius: 8px;
  position: relative;
}

.doctor-bubble {
  background-color: #fff;
  color: #333;
}

.user-bubble {
  background-color: #4cd964;
  color: #fff;
}

.message-content {
  word-wrap: break-word;
  line-height: 1.5;
}

.message-image {
  max-width: 100%;
  border-radius: 4px;
}

.message-time {
  font-size: 12px;
  margin-top: 5px;
  text-align: right;
  opacity: 0.7;
}

.chat-footer {
  display: flex;
  flex-direction: column;
  padding: 10px;
  background-color: #fff;
  border-top: 1px solid #eee;
}

.tool-bar {
  display: flex;
  padding: 5px 0;
}

.tool-item {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
}

.input-area {
  display: flex;
  align-items: center;
}

.message-input {
  flex: 1;
  min-height: 40px;
  max-height: 120px;
  padding: 8px 12px;
  border: 1px solid #eee;
  border-radius: 20px;
  background-color: #f5f5f5;
  resize: none;
}

.send-btn {
  width: 60px;
  height: 36px;
  margin-left: 10px;
  background-color: #4cd964;
  color: #fff;
  border-radius: 18px;
  font-size: 14px;
  line-height: 36px;
}

.chat-footer.ended {
  padding: 15px;
  justify-content: center;
  align-items: center;
  color: #999;
  font-size: 14px;
}
</style>